/*
 * @Copyright: Copyright (c) 2030 吴周海
 * @Author: wzh200x@126.com
 * @Date: 2025-10-09 16:02:43
 * @LastEditors: wzh200x@126.com
 * @LastEditTime: 2025-10-09 16:04:23
 * @FilePath: \goWebServer\goGameWebServer\internal\model\entity\entityModel.go
 * @Description: 文件功能描述
 */
package entity

import (
	"goGameWebServer/internal/common/logger"
	"goGameWebServer/internal/defines/dataType"
	"goGameWebServer/internal/interfaces"
	"goGameWebServer/internal/manager/databasemanager"
)

type EntityModel struct {
	BaseModel
	EntityData interfaces.IEntityModelData // 数据
	UpdateFlag bool                        // 更新标识
}

func (entityModel *EntityModel) LoadEntityDataFromDB(records interface{}) error {
	panic("implement me")
}

func (entityModel *EntityModel) UpdateEntityData(isSyncToDB bool) error {
	if isSyncToDB {
		err := entityModel.SaveEntityDataToDB()
		if err != nil {
			return err
		}
	} else {
		entityModel.UpdateFlag = true
	}
	return nil
}

func (entityModel *EntityModel) SetEntityData(d interfaces.IEntityModelData) {
	entityModel.EntityData = d
}

func (entityModel *EntityModel) GetEntityData() interfaces.IEntityModelData {
	return entityModel.EntityData
}

func (entityModel *EntityModel) SyncEntityDataToDB() error {
	if entityModel.UpdateFlag {
		err := entityModel.SaveEntityDataToDB()
		if err != nil {
			return err
		}
		entityModel.UpdateFlag = false
	}
	return nil
}

func (entityModel *EntityModel) CreateDataToDB() error {
	base, err := databasemanager.ManagerDatabase().DefaultDataBase()
	if err != nil {
		return err
	}
	dbid, err := base.GetDb().Model(entityModel.Template).Data(entityModel.EntityData).OmitEmpty().InsertAndGetId()
	entityModel.SetEntityDBID(dataType.TypeDataBaseId(dbid))
	if err != nil {
		logger.LoggerIns().Errorf("CreateDataToDB model %s error", entityModel.Name)
	}
	return err
}

func (entityModel *EntityModel) SaveEntityDataToDB() error {
	if entityModel.EntityData == nil || entityModel.EntityDBID == 0 {
		return nil
	}
	base, err := databasemanager.ManagerDatabase().DefaultDataBase()
	if err != nil {
		return err
	}
	_, err = base.GetDb().Model(entityModel.Template).Data(entityModel.EntityData).OmitEmpty().Save()
	if err != nil {
		logger.LoggerIns().Errorf("SyncEntityDataToDB model %s error dbid:%s", entityModel.Name, entityModel.EntityDBID)
	}
	return err
}

func (entityModel *EntityModel) Reset() {
	entityModel.BaseModel.Reset()
	entityModel.EntityData.Reset()
	entityModel.UpdateFlag = false
}

func NewEntityModel(name string) EntityModel {
	return EntityModel{
		BaseModel:  NewBaseModel(name, 0),
		EntityData: nil,
		UpdateFlag: false,
	}
}
